/* eslint-disable no-console */
/* eslint-disable react/jsx-no-bind */
import { Card } from 'antd'
import { useCallback, useEffect, useState } from 'react'
import { render } from 'react-dom'

import SlardarLite, { createInstance } from '@slardar/sdk-lite'

window.Slardar = SlardarLite as any
const $root = document.querySelector('#app')

const App = () => {
  const onClick = useCallback(() => {
    throw Error('custom error')
  }, [])

  const onClickAjax = useCallback(() => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://localhost:8080/slardar-lite.html')
    xhr.send()
    SlardarLite.config({ pid: 'new' })
  }, [])

  const onClickFetch = useCallback(() => {
    window.fetch('http://localhost:8080/slardar-lite.html')
  }, [])

  const onClickStatic = useCallback(() => {
    const imgEle = document.createElement('img')
    imgEle.src = 'http://localhost:8080/unexist.png'
    document.body.appendChild(imgEle)
  }, [])

  const onClickLongTask = useCallback(() => {
    const time = Date.now()
    // eslint-disable-next-line no-constant-condition
    while (true) {
      if (Date.now() - time > 50) {
        break
      }
    }
  }, [])

  const [cls, setCls] = useState(false)

  setTimeout(setCls, 1000, true)

  // 通过 async 函数产生一个异步错误
  const onClickJsErr = useCallback(() => {
    const a = [1, 2, 3]
    for (let i = 0; i < 5; i++) {
      a[i].toString()
    }
  }, [])

  const [enableImage, setEnableImage] = useState(false)
  const onStaticErr = useCallback(() => {
    setEnableImage(true)
    const imgEle = document.createElement('img')
    imgEle.src = '/unexist.png?a=1&b=2#hash'
    document.body.appendChild(imgEle)
  }, [])

  useEffect(() => {
    Promise.reject('unhandle rejection')
  }, [])

  const onPerfClick = () => {
    setCls(!cls)
  }

  const onClickCustomEvent = useCallback(() => {
    SlardarLite.sendEvent?.({
      name: '123',
      metrics: {
        a: 3,
      },
      categories: {
        b: '3',
      },
    })
  }, [])

  const onClickCustomLog = useCallback(() => {
    SlardarLite.sendLog?.({
      content: '234',
      extra: {
        a: 3,
        b: '3',
      },
      level: 'error',
    })
  }, [])

  const onClickCustomMetric = useCallback(() => {
    SlardarLite.sendCustomPerfMetric?.({ name: 'tti', type: 'perf', value: 123 })
  }, [])

  const onClickCustomException = useCallback(() => {
    SlardarLite.captureException?.(new Error('custom error'))
  }, [])

  const onClickCustomContext = useCallback(() => {
    SlardarLite.context?.set('a', 'b')
  }, [])

  const onClickCustomPV = useCallback(() => {
    SlardarLite.sendPageview?.('ppp')
  }, [])

  const onClickCustomPID = useCallback(() => {
    SlardarLite.config({ pid: 'ppp' })
  }, [])

  const [state, setState] = useState({ a: { b: '3' } })
  const onClickBlank = useCallback(() => {
    setState(3 as any)
  }, [])

  const onClickRAFError = () => {
    window.requestAnimationFrame(() => {
      throw new Error('raf error')
    })
  }

  const onClickRICError = () => {
    window.requestIdleCallback(() => {
      throw new Error('ric error')
    })
  }

  const onClickEventHandlerError = () => {
    document.body.addEventListener('click', () => {
      throw new Error('click error')
    })

    document.body.click()
  }

  const onClickXHRError = () => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', 'unexist')
    xhr.onreadystatechange = () => {
      throw new Error('xhr error')
    }
    xhr.send()
  }

  const onClickInstance2 = () => {
    const instance2 = createInstance({ bid: 'instance2' })
    instance2.sendCustomPerfMetric?.({ name: 'perf', value: 3 })
  }

  const onClickStart = () => {
    SlardarLite.start()
  }

  return (
    <div className="app">
      <div id="click" onClick={onClick}>
        Click
      </div>
      <div id="ajax_click" onClick={onClickAjax}>
        Ajax_Click
      </div>
      <div id="fetch_click" onClick={onClickFetch}>
        Fetch_Click
      </div>
      <div id="static_click" onClick={onClickStatic}>
        Static_Click
      </div>
      <div id="longtask_click" onClick={onClickLongTask}>
        LongTask_Click
      </div>
      <div id="perf_click" onClick={onPerfClick}>
        Perf cls position
        {cls && <div style={{ height: 100 }} />}
      </div>
      {[...new Array(22).keys()].map((i) => (
        <div key={i} id={`breadcrumb_item_${i}`}>{`breadcrumb ${i}`}</div>
      ))}
      <div id="jserr_with_breadcrumb" onClick={onClickJsErr}>
        JS_Error_With_Breadcrumb
      </div>
      <div id="static_err" onClick={onStaticErr}>
        Static_Error
      </div>
      <Card>
        <h1>Slardar SDK 222</h1>
        <p>Testing by cypress</p>
        {enableImage ? <img src="https://s3a.pstatp.com/rangers/test.png" style={{ width: 100, height: 100 }} /> : null}
      </Card>
      <div id="custom_event_click" onClick={onClickCustomEvent}>
        Custom_Event_Click
      </div>
      <div id="custom_log_click" onClick={onClickCustomLog}>
        Custom_Log_Click
      </div>
      <div id="custom_metric_click" onClick={onClickCustomMetric}>
        Custom_Metric_Click
      </div>
      <div id="custom_exception_click" onClick={onClickCustomException}>
        Custom_Exception_Click
      </div>
      <div id="custom_pv_click" onClick={onClickCustomPV}>
        Custom_PV_Click
      </div>
      <div id="custom_context_click" onClick={onClickCustomContext}>
        Custom_Context_Click
      </div>
      <div id="custom_pid_click" onClick={onClickCustomPID}>
        Custom_PID_Click
      </div>
      <div id="blank_click" onClick={onClickBlank}>
        Blank_Click
        {state.a.b}
      </div>
      <div id="raf_error" onClick={onClickRAFError}>
        RAF error
      </div>
      <div id="ric_error" onClick={onClickRICError}>
        ric error
      </div>
      <div id="click_error" onClick={onClickEventHandlerError}>
        click error
      </div>
      <div id="xhr_error" onClick={onClickXHRError}>
        xhr error
      </div>
      <div id="instance2" onClick={onClickInstance2}>
        instance2
      </div>
      <div id="start" onClick={onClickStart}>
        start
      </div>
    </div>
  )
}

const delay = new URL(location.href).searchParams.get('delay')
const blank = new URL(location.href).searchParams.get('blank')

;(() => {
  if (blank) {
    return
  }
  if (delay) {
    setTimeout(() => {
      render(<App />, $root!)
    }, parseInt(delay))
  } else {
    render(<App />, $root!)
  }
})()
